package service

import (
	"context"
	"google.golang.org/protobuf/types/known/wrapperspb"

	pb "gitee.com/shuokeyun/item-service/api/v1"
	"gitee.com/shuokeyun/item-service/internal/domain"
)

// ItemService .
type ItemService struct {
	pb.UnimplementedItemServer
	item domain.ItemUsecase
}

// NewItemServer .
func NewItemServer(item domain.ItemUsecase) pb.ItemServer {
	return &ItemService{
		item: item,
	}
}

// CreateItem 创建项目
func (s *ItemService) CreateItem(ctx context.Context, req *pb.CreateItemRequest) (*wrapperspb.BoolValue, error) {
	return &wrapperspb.BoolValue{
		Value: true,
	}, nil
}

// UpdateItem 编辑项目
func (s *ItemService) UpdateItem(ctx context.Context, req *pb.UpdateItemRequest) (*wrapperspb.BoolValue, error) {
	return &wrapperspb.BoolValue{
		Value: true,
	}, nil
}

// DeleteItem 删除项目
func (s *ItemService) DeleteItem(ctx context.Context, req *pb.DeleteItemRequest) (*wrapperspb.BoolValue, error) {
	err := s.item.DeleteItem(ctx, req.Code, req.Brand, req.PriceArea)
	if err != nil {
		return nil, err
	}
	return &wrapperspb.BoolValue{
		Value: true,
	}, nil
}

// GetItem 获取单个项目
func (s *ItemService) GetItem(ctx context.Context, req *pb.GetItemRequest) (*pb.GetItemReply, error) {
	do, err := s.item.GetItem(ctx, req.Code, req.Brand, req.PriceArea, req.GetFieldMask().GetPaths())
	if err != nil {
		return nil, err
	}
	return doConvItemReply(do), nil
}

// ListItem 获取项目列表
func (s *ItemService) ListItem(ctx context.Context, req *pb.ListItemRequest) (*pb.ListItemReply, error) {
	if req.PageSize < 0 {
		req.PageSize = 20
	} else if req.PageSize > 1000 {
		req.PageSize = 1000
	}
	if req.PageNo < 1 {
		req.PageNo = 1
	}
	list, total, err := s.item.ListItems(ctx, &domain.SearchItemList{
		Keywords:  req.Keywords,
		Code:      req.Code,
		Brand:     req.Brand,
		PriceArea: req.PriceArea,
		Status:    int8(req.Status),
		PageSize:  req.PageSize,
		PageNo:    req.PageNo,
	})
	if err != nil {
		return nil, err
	}
	return &pb.ListItemReply{
		TotalSize: total,
		PageNo:    req.PageNo,
		PageSize:  req.PageSize,
		Data:      doConvListItemReply(list),
	}, nil
}

// GetItems 获取多个项目
func (s *ItemService) GetItems(ctx context.Context, req *pb.GetItemsRequest) (*pb.GetItemsReply, error) {
	list, err := s.item.GetItems(ctx, req.GetCode(), req.GetBrand(), req.GetPriceArea(), req.GetFieldMask().GetPaths())
	if err != nil {
		return nil, err
	}
	return &pb.GetItemsReply{
		Data: doConvListItemReply(list),
	}, nil
}
